<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="采购单号" prop="ordersNumber">
        <el-input v-model="queryParams.ordersNumber" placeholder="请输入采购单号" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="SKU" prop="sku">
        <el-input v-model="queryParams.sku" placeholder="请输入sku" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="1688运单号" label-width="100px" prop="orderNo1688">
        <el-input v-model="queryParams.orderNo1688" placeholder="请输入1688运单号" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="queryParams.remark" placeholder="请输入备注" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item> -->

      <el-form-item label="状态筛选" prop="statusFilter">
        <el-select v-model="queryParams.statusFilter" placeholder="请选择状态" clearable>
          <!-- 付款状态分组 -->
          <el-option-group label="付款状态">
            <el-option v-for="dict in dict.type.payment_status" :key="'pay-' + dict.value" :label="dict.label"
              :value="'pay-' + dict.value" />
          </el-option-group>

          <!-- 申请状态分组 -->
          <el-option-group label="退款状态">
            <el-option v-for="dict in dict.type.payment_return_status" :key="'review-' + dict.value" :label="dict.label"
              :value="'return-' + dict.value" />
          </el-option-group>
        </el-select>
      </el-form-item>

      <el-form-item label="入库状态" prop="searchInboundStatus">
        <el-select v-model="queryParams.searchInboundStatus" placeholder="请选择入库状态" clearable>
          <el-option v-for="dict in dict.type.inbound_status" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="订单/撤回状态" prop="orderStatusFilter" style="white-space: nowrap">
        <el-select v-model="queryParams.orderStatusFilter" placeholder="请选择状态" clearable style="margin-left: 25px">
          <!-- 订单状态分组 -->
          <el-option-group label="订单状态">
            <el-option v-for="dict in dict.type.procured_orders_status" :key="'orders-' + dict.value"
              :label="dict.label" :value="'orders-' + dict.value" />
          </el-option-group>

          <!-- 撤回状态分组 -->
          <el-option-group label="撤回状态">
            <el-option v-for="dict in dict.type.tb_delete_status" :key="'delete-' + dict.value" :label="dict.label"
              :value="'delete-' + dict.value" />
          </el-option-group>
        </el-select>
      </el-form-item>

      <el-form-item>
        <!-- 搜索输入框 -->
        <el-input v-model="queryParams.searchContent" placeholder="请输入搜索内容" clearable style="width: 300px"
          @keyup.enter.native="handleQuery">
          <!-- 下拉选择搜索条件 -->
          <el-select v-model="queryParams.searchType" slot="prepend" placeholder="请选择搜索条件" style="width: 100px">
            <el-option label="采购单号" value="1"></el-option>
            <el-option label="SKU" value="2"></el-option>
            <el-option label="1688订单号" value="3"></el-option>
            <el-option label="1688运单号" value="5"></el-option>
            <el-option label="备注" value="4"></el-option>
          </el-select>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-plus" size="mini" @click="handleAddBatch"
          :disabled="batchOrderNumbers.length === 0" v-hasPermi="['product:ProcuredOrders:add']">批量申请付款</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-folder-checked" size="mini" @click="underReview"
          v-hasPermi="['product:ProcuredOrders:add']">审核</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['product:ProcuredOrders:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="ProcuredOrdersList" @selection-change="handleSelectionChange"
      style="width: 100%" :row-class-name="tableRowClassName">
      <el-table-column type="selection" min-width="55" align="center" />
      <el-table-column label="采购单号" align="center" width="200" prop="ordersNumber">
        <template slot-scope="scope">
          <span>{{ scope.row.ordersNumber || "-" }}</span>
          <br />
          <span>{{ scope.row.orderNo1688 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="采购计划号" align="center" width="150" prop="planNumber">
        <template slot-scope="scope">
          <span>{{ scope.row.planNumber || "-" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="快递单号" align="center" width="150" prop="expressNumber">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.expressNumber || '-'" placement="top">
            <span v-if="scope.row.expressNumber">
              {{ scope.row.expressNumber.slice(0, 10) }}
              <span v-if="scope.row.expressNumber.length > 10">...</span>
            </span>
            <span v-else>-</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="寄往仓库" align="center" width="150" prop="companyName">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.companyName || '无'" placement="top">
            <span v-if="scope.row.companyName">
              {{ scope.row.companyName.slice(0, 10) }}
              <span v-if="scope.row.companyName.length > 10">...</span>
            </span>
            <span v-else>-</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="下单" align="center" min-width="150">
        <template slot-scope="scope">
          <span>{{ scope.row.approver || "-" }}</span><br />
          <span>{{
            parseTime(scope.row.approvedTime, "{y}-{m}-{d}") || "-"
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="总件数" align="center" prop="total" width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.total || "-" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="采购员" align="center" prop="userName" width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.userName || "-" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="status" width="120">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.procured_orders_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="付款/退款状态" align="center" prop="paymentStatus" width="180">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.payment_status" :value="scope.row.paymentStatus" />
          <dict-tag :options="dict.type.payment_return_status" :value="scope.row.returnStatus" />
          <el-badge :value="scope.row.solveCount" :hidden="!scope.row.solveCount || scope.row.solveCount <= 0">
            <el-button type="text" @click="applicationRecords(scope.row)">申请记录</el-button>
          </el-badge>
        </template>
      </el-table-column>
      <el-table-column label="入库状态" align="center" prop="inboundStatus" width="120">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.inbound_status" :value="scope.row.inboundStatus" />
        </template>
      </el-table-column>
      <el-table-column label="应付金额" align="center" prop="amountDue" width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.amountDue || "-" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="运费" align="center" prop="freight" width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.freight || "-" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="批次号" align="center" prop="purchaseBatchNumber" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.purchaseBatchNumber || "-" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="入库总数量" align="center" prop="inboundNumber" width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.inboundNumber || "-" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="撤回备注" align="center" prop="revokeRemark" width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.revokeRemark || "-" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.remark || "-" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180" fixed="right">
        <template slot-scope="scope">
          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-hasPermi="[
            'product:ProcuredOrders:edit',
            'product:ProcuredOrders:remove',
            'product:RequestAdvance:add',
          ]">
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="handleUpdate" icon="el-icon-edit"
                v-hasPermi="['product:ProcuredOrders:edit']">详情</el-dropdown-item>
              <el-dropdown-item v-if="
                Number(scope.row.deleteStatus) === 0 &&
                ![2, 4].includes(Number(scope.row.paymentStatus))
              " command="handleQuash" icon="el-icon-document-delete" v-hasPermi="['procured:plan:batch']">
                申请付款
              </el-dropdown-item>
              <el-dropdown-item v-if="
                Number(scope.row.deleteStatus) === 0 &&
                [3, 4].includes(Number(scope.row.paymentStatus))
              " command="handleReturn" icon="el-icon-document-delete" v-hasPermi="['procured:plan:batch']">
                申请退款
              </el-dropdown-item>
              <el-dropdown-item command="handleCancel" icon="el-icon-edit" v-if="
                scope.row.revokeRemark == null &&
                scope.row.paymentStatus === '0'
              " v-hasPermi="['product:ProcuredOrders:edit']">撤回订单</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <br />
          <el-button type="text" v-if="Number(scope.row.deleteStatus) === 0"
            @click="handleTrace(scope.row)">跟踪记录</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改采购订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" label-width="80px">
        <el-tabs v-model="activeName" type="card">
          <el-tab-pane label="基础信息" name="first">
            <el-row>
              <el-col :span="6">
                <el-form-item label="采购单号:" prop="ordersNumber">
                  <el-input v-model="form.ordersNumber" placeholder="请输入计划单号" :disabled="true" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="快递单号" prop="expressNumber">
                  <el-input v-model="form.expressNumber" placeholder="请输入快递单号" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="总件数" prop="total">
                  <el-input v-model="form.total" placeholder="请输入总件数" :disabled="true" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="应付金额" prop="amountDue">
                  <el-input v-model="form.amountDue" placeholder="请输入应付金额" :disabled="true" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="6">
                <el-form-item label="计划单号:" prop="planNumber">
                  <el-input v-model="form.planNumber" placeholder="请输入计划单号" :disabled="true" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="采购日期" prop="planDate">
                  <el-date-picker clearable v-model="form.planDate" type="date" value-format="yyyy-MM-dd"
                    placeholder="请选择采购日期" style="width: 210px" :default-value="new Date().toISOString().split('T')[0]"
                    :disabled="true">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <!-- <el-col :span="6">
                <el-form-item label="供应商" prop="vendorId">
                  <treeselect v-model="form.vendorId" :options="vendorOptions" :show-count="true" placeholder="请输入供应商"
                    @input="autoFillModelVendorId" :disabled="true" />
                </el-form-item>
              </el-col> -->
              <el-col :span="6">
                <el-form-item label="采购公司" prop="companyId">
                  <treeselect v-model="form.companyId" :options="companyOptions" :show-count="true"
                    placeholder="请输入采购公司" :disabled="true" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="批次号" prop="purchaseBatchNumber">
                  <el-input v-model="form.purchaseBatchNumber" :disabled="true" placeholder="批次号" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="采购部门:" prop="deptName">
                  <el-input v-model="form.deptName" placeholder="请输入采购部门" :disabled="true" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="采购人员" prop="userName">
                  <el-input v-model="form.userName" placeholder="请输入采购人员" :disabled="true" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="预入仓库" prop="warehouseId">
                  <treeselect v-model="form.warehouseId" :options="warehouseOptions" :show-count="true"
                    placeholder="请输入预入仓库" :disabled="true" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="运费" prop="freight">
                  <el-input v-model="form.freight" placeholder="请输入运费" :disabled="true" />
                </el-form-item>
              </el-col>
              <!-- <el-col :span="6">
                <el-form-item label="货币单位" prop="monetaryId">
                  <treeselect v-model="form.monetaryId" :options="monetaryOptions" :show-count="true"
                    placeholder="请输入货币单位" :disabled="true" />
                </el-form-item>
              </el-col> -->
            </el-row>
            <el-row>
              <!-- <el-col :span="6">
                <el-form-item label="汇率" prop="currency">
                  <el-input v-model="form.currency" placeholder="请输入汇率" :disabled="true" />
                </el-form-item>
              </el-col> -->
            </el-row>
            <!-- 备注展示框 -->
            <el-row>
              <el-col :span="24">
                <el-form-item label="备注展示:" prop="remark">
                  <el-input v-model="form.remark" type="textarea" :rows="4" :disabled="true"
                    class="remark-display-box"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-divider content-position="center">采购订单商品信息</el-divider>
            <el-row :gutter="10" class="mb8"> </el-row>
            <el-table :data="ordersProductList" :row-class-name="rowOrdersProductIndex"
              @selection-change="handleOrdersProductSelectionChange" ref="ordersProduct" height="600px"
              :span-method="spanMethod">
              <el-table-column type="selection" width="50" align="center" :selectable="(row) =>
                row.returnCompletedStatus !== 1 &&
                row.returnCompletedStatus !== '1'
                " />
              <el-table-column label="序号" align="center" prop="index" min-width="50" />
              <el-table-column label="图片" prop="imagePath" align="center" min-width="200">
                <template slot-scope="scope">
                  <div class="image-container">
                    <image-preview v-for="(image, index) in scope.row.imagePath" :key="index" :src="image" :width="50"
                      :height="50" class="image-item" />
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="产品名称" prop="productName" min-width="150">
                <template slot-scope="scope">
                  <TooltipCell :value="scope.row.productName" />
                </template>
              </el-table-column>
              <el-table-column label="SKU" prop="sku" min-width="150">
                <template slot-scope="scope">
                  <TooltipCell :value="scope.row.sku" />
                </template>
              </el-table-column>
              <el-table-column label="GTIN" prop="gtin" min-width="150">
                <template slot-scope="scope">
                  <TooltipCell :value="scope.row.gtin" />
                </template>
              </el-table-column>
              <el-table-column label="数量" prop="transferableNumber" min-width="150">
                <template slot-scope="scope">
                  <TooltipCell :value="scope.row.transferableNumber" />
                </template>
              </el-table-column>
              <el-table-column label="合计数量" prop="totalQuantity" align="center" min-width="100">
                <template slot-scope="scope">
                  <!-- 根据当前行的 sku 去计算属性 skuNumberSums 里取值 -->
                  <span>{{ skuNumberSums[scope.row.sku] }}</span>
                </template>
              </el-table-column>
              <el-table-column label="产品价格" prop="productPrice" min-width="150">
                <template slot-scope="scope">
                  <TooltipCell :value="scope.row.productPrice" />
                </template>
              </el-table-column>
              <el-table-column label="金额" prop="amount" min-width="150">
                <template slot-scope="scope">
                  <span>
                    <!-- 假设该行为分组第一行，显示汇总金额，否则为空 -->
                    <span v-if="isFirstRowInGroup(scope.row, 'sku')">
                      {{
                        skuAggregates[scope.row.sku]
                          ? skuAggregates[scope.row.sku].amountSum.toFixed(2)
                          : "-"
                      }}
                    </span>
                  </span>
                </template>
              </el-table-column>

              <!-- 税率 -->
              <el-table-column label="税率" prop="productRate" :min-width="100">
                <template slot-scope="scope">
                  <el-tooltip class="item" effect="dark" :content="scope.row.productRate != null
                    ? scope.row.productRate.toString() + '%'
                    : '-'
                    " placement="top">
                    <span>{{
                      scope.row.productRate != null
                        ? scope.row.productRate + "%"
                        : "-"
                    }}</span>
                  </el-tooltip>
                </template>
              </el-table-column>
              <!-- 税额（新加列） -->
              <el-table-column label="税额" prop="tax" min-width="150">
                <template slot-scope="scope">
                  <span v-if="isFirstRowInGroup(scope.row, 'sku')">
                    {{
                      skuAggregates[scope.row.sku]
                        ? skuAggregates[scope.row.sku].taxSum.toFixed(2)
                        : "-"
                    }}
                  </span>
                </template>
              </el-table-column>
              <!-- 含税金额（新加列） -->
              <el-table-column label="含税金额" prop="taxIncluded" min-width="150">
                <template slot-scope="scope">
                  <span v-if="isFirstRowInGroup(scope.row, 'sku')">
                    {{
                      skuAggregates[scope.row.sku]
                        ? skuAggregates[scope.row.sku].taxIncludedSum.toFixed(2)
                        : "-"
                    }}
                  </span>
                </template>
              </el-table-column>
              <!-- 单品成本 -->
              <el-table-column label="单品成本" :min-width="120">
                <template slot-scope="scope">
                  <el-tooltip class="item" effect="dark" :content="scope.row.transferableNumber &&
                    scope.row.totalCost != null
                    ? (
                      scope.row.totalCost / scope.row.transferableNumber
                    ).toFixed(2)
                    : '-'
                    " placement="top">
                    <span>
                      {{
                        scope.row.transferableNumber &&
                          scope.row.totalCost != null
                          ? (
                            scope.row.totalCost / scope.row.transferableNumber
                          ).toFixed(2)
                          : "-"
                      }}
                    </span>
                  </el-tooltip>
                </template>
              </el-table-column>
              <!-- 总成本 -->
              <el-table-column label="总成本" prop="totalCost" min-width="150">
                <template slot-scope="scope">
                  <span v-if="isFirstRowInGroup(scope.row, 'sku')">
                    {{
                      skuAggregates[scope.row.sku] &&
                        skuAggregates[scope.row.sku].totalCostSum
                        ? skuAggregates[scope.row.sku].totalCostSum.toFixed(2)
                        : "-"
                    }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="供应商" prop="vendorId" min-width="270">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.orderNo1688" disabled placeholder="" clearable
                    style="margin-bottom: 8px" />
                  <el-select v-model="scope.row.vendorId" disabled placeholder="" filterable size="medium"
                    style="min-width: 250px">
                    <el-option v-for="item in vendorOptions" :key="item.id" :label="item.label" :value="item.id">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>

              <el-table-column label="交付时间" prop="deliveryTime" min-width="230">
                <template slot-scope="scope">
                  <el-date-picker v-model="scope.row.deliveryTime" disabled type="datetime" placeholder=""
                    format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss">
                  </el-date-picker>
                </template>
              </el-table-column>

              <!-- 货币单位列 -->
              <el-table-column label="货币单位" prop="monetaryId" min-width="150">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.monetaryId" placeholder="" disabled
                    @change="handleCurrencyChangeRow(scope.row)">
                    <el-option v-for="item in monetaryOptions" :key="item.id" :label="item.label" :value="item.id">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>

              <!-- 新增每个产品的汇率输入 -->
              <el-table-column label="汇率" prop="currency" min-width="130">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.currency" disabled placeholder=""
                    @input="handleRateChangeRow(scope.row)" />
                </template>
              </el-table-column>
              <!-- 新增每个产品的运费输入 -->
              <el-table-column label="运费" prop="freight" min-width="130">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.freight" disabled placeholder="" />
                </template>
              </el-table-column>
              <el-table-column label="入库数量" prop="storageNumber" min-width="150">
                <template slot-scope="scope">
                  <el-tooltip :content="scope.row.storageNumber || '-'" placement="top"
                    :disabled="!scope.row.storageNumber">
                    <span>{{ scope.row.storageNumber || "-" }}</span>
                  </el-tooltip>
                </template>
              </el-table-column>
              <el-table-column label="备注" prop="productRemark" min-width="150">
                <template slot-scope="scope">
                  <el-tooltip :content="scope.row.productRemark || '-'" placement="top"
                    :disabled="!scope.row.productRemark">
                    <span>{{ scope.row.productRemark || "-" }}</span>
                  </el-tooltip>
                </template>
              </el-table-column>
              <el-table-column label="操作进度" prop="operationLog" min-width="320">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.operationLog" type="textarea" size="small" :rows="5" />
                </template>
              </el-table-column>
            </el-table>
            <!-- 合计金额显示区域 -->
            <el-row style="margin-top: 10px">
              <el-col :span="24">
                <div class="total-amount-box">
                  <span class="total-label">合计成本</span>
                  <span class="total-value">{{ totalCost }}</span>
                </div>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="合同备注" name="second">
            <el-row>
              <el-col :span="24">
                <editor v-model="form.contract" :min-height="192" ref="quillEditor" />
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <!-- <el-button type="primary" @click="submitForm">确 定</el-button> -->
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 申请记录 -->
    <el-dialog :title="titleRequest" :visible.sync="openRequest" width="1600px" append-to-body
      :close-on-click-modal="false">
      <el-form :model="queryParam" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="付款类型" prop="paymentType">
          <el-select v-model="queryParam.paymentType" placeholder="请选择类型" clearable>
            <el-option v-for="dict in dict.type.request_payment_type" :key="dict.value" :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="付款状态" prop="paymentStatus">
          <el-select v-model="queryParam.paymentStatus" placeholder="请选择付款状态" clearable>
            <el-option v-for="dict in dict.type.request_payment_status" :key="dict.value" :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="申请状态" prop="paymentReviewStatus">
          <el-select v-model="queryParam.paymentReviewStatus" placeholder="请选择申请状态" clearable>
            <el-option v-for="dict in dict.type.payment_review_status" :key="dict.value" :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQueryRequest">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQueryRequest">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8" v-if="1 == 2">
        <el-col :span="1.5">
          <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleRequest"
            v-hasPermi="['product:PaymentRequest:cancel']">批量取消申请</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getPaymentRequestList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="PaymentRequestList" @selection-change="handleSelectionChange" height="500px">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column width="55" align="center">
          <template slot-scope="scope">
            <el-button type="text" width="55" @click.stop="paymentRequestLog(scope.row)">日志</el-button>
          </template>
        </el-table-column>
        <el-table-column label="采购订单号" align="center" prop="ordersNumber" />
        <el-table-column label="申请状态" align="center" prop="cancelStatus">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.payment_review_status" :value="scope.row.paymentReviewStatus" />
          </template>
        </el-table-column>
        <el-table-column label="类型" align="center" prop="paymentType">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.request_payment_type" :value="scope.row.paymentType" />
          </template>
        </el-table-column>
        <el-table-column label="申请金额" align="center">
          <template v-slot="scope">
            {{ formatApplyAmount(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column label="原始金额" align="center" prop="amountDue" />
        <el-table-column label="状态" align="center" prop="paymentStatus">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.request_payment_status" :value="scope.row.paymentStatus" />
          </template>
        </el-table-column>
        <el-table-column label="水单图片" prop="waterBillImg" align="center">
          <template slot-scope="scope">
            <div class="image-container">
              <image-preview v-if="scope.row.waterBillImg" :src="scope.row.waterBillImg" :width="50" :height="50"
                class="image-item" />
              <el-button v-if="scope.row.waterBillImg" type="text" size="mini" icon="el-icon-download"
                @click="downloadImage(scope.row.waterBillImg)">
                下载
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="预付款/应付款/退款备注" align="center" width="180px">
          <template slot-scope="scope">
            {{
              scope.row.prepaymentRemark ||
              scope.row.otherFeeRemark ||
              scope.row.returnRemark
            }}
          </template>
        </el-table-column>
        <el-table-column label="申请人/申请日期" align="center">
          <template slot-scope="scope">
            {{ scope.row.applicant }}<br />{{
              parseTime(scope.row.applicationTime, "{y}-{m}-{d}")
            }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleRequestSolve(scope.row)"
              v-hasPermi="['product:PaymentRequest:solve']" v-if="scope.row.solveStatus == 0">驳回处理</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="totals > 0" :total="totals" :page.sync="queryParam.pageNum" :limit.sync="queryParam.pageSize"
        @pagination="getPaymentRequestList" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelRequest">取消</el-button>
      </div>
    </el-dialog>

    <!-- 跟踪记录 -->
    <el-dialog :title="titleTrace" :visible.sync="openTrace" width="800px" append-to-body :close-on-click-modal="false">
      <el-form ref="formTrace" :model="formTrace" label-width="101px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="预计到达日期:" prop="arriveDate">
              <el-date-picker clearable v-model="formTrace.arriveDate" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择预计到达日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="快递单号:" prop="expressNumber">
              <el-input v-model="formTrace.expressNumber" placeholder="请输入快递单号" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-input v-model="formTrace.expressRemark" type="textarea" :rows="20" />
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormTrace">确 定</el-button>
        <el-button @click="cancelTrace">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 申请付款 -->
    <el-dialog :title="titleQuash" :visible.sync="openQuash" width="1000px" append-to-body
      :close-on-click-modal="false">
      <el-form ref="formQuash" :model="formQuash" label-width="110px" :rules="rules">
        <el-row>
          <el-col :span="6">
            <el-form-item label="采购订单号:" prop="ordersNumber">
              {{ this.formQuash.ordersNumber }}
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="运费:" prop="freight">
              {{ this.formQuash.freight }}
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="优惠金额:" prop="discountAmount">
              {{ this.formQuash.discountAmount }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="汇率:" prop="currency">
              {{ this.formQuash.currency }}
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="币种:" prop="monetaryName">
              {{ this.formQuash.monetaryName }}
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="原应付金额:" prop="monetaryName">
              {{ this.formQuash.amountDue }}
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="付款方式" prop="paymentType">
          <el-radio-group v-model="formQuash.paymentType" @change="handlePaymentTypeChange">
            <el-radio label="0">预付款</el-radio>
            <el-radio label="1">应付款</el-radio>
          </el-radio-group>
        </el-form-item>

        <div v-if="formQuash.paymentType === '0'">
          <el-row>
            <el-col :span="24">
              <el-form-item label="付款周期:" prop="prepaymentCycle">
                <el-date-picker clearable v-model="formQuash.prepaymentCycle" type="date" value-format="yyyy-MM-dd"
                  placeholder="请选付款周期" style="width: 210px" :default-value="new Date().toISOString().split('T')[0]">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="预付金额:" prop="prepaymentAmount">
                <el-input v-model="formQuash.prepaymentAmount" type="number" style="width: 210px" placeholder="请输入预付金额"
                  @input="autoFillModel" />&nbsp;<span>最大可申请金额：{{ totalAmountDue }}</span>
                <br />
                <span v-if="formQuash.prepaymentAmount > totalAmountDue" style="color: red">预付金额超出最大可申请金额，请重新输入！</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注:" prop="prepaymentRemark">
                <el-input v-model="formQuash.prepaymentRemark" placeholder="请输入备注" type="textarea" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div v-if="formQuash.paymentType === '1'">
          <el-row>
            <el-col :span="12">
              <el-form-item label="应付金额:">
                <el-input v-model="this.totalAmountDue" type="number" readonly style="width: 210px" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="其他费用:" prop="otherFeeAmount">
                <el-input placeholder="请输入金额" v-model="formQuash.otherFeeAmount" class="input-with-select"
                  :style="{ width: '300px' }">
                  <el-select v-model="formQuash.otherFeeType" slot="prepend" placeholder="请选择"
                    :style="{ width: '100px' }" @change="handleOtherFeeTypeChange">
                    <el-option label="请选择" value=""></el-option>
                    <el-option label="增加" value="增加"></el-option>
                    <el-option label="减少" value="减少"></el-option>
                  </el-select>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="备注:" prop="otherFeeRemark" label-width="100px">
                <el-input placeholder="请输入其他费用备注" v-model="formQuash.otherFeeRemark" type="textarea"
                  :style="{ width: '650px' }"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" v-if="this.totalAmountDue !== 0" @click="submitFormQuash">
          确 定
        </el-button>
        <el-button @click="cancelQuash">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 批量申请付款弹窗 -->
    <el-dialog title="确认批量申请付款" :visible.sync="dialogVisible" width="30%">
      <span>您确定【{{ batchOrderNumbers.join("，") }}】批量申请应付款吗？</span>

      <!-- 弹窗底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </span>
    </el-dialog>

    <!-- 审核申请 -->
    <el-dialog :title="audit" :visible.sync="openAudit" width="1200px" append-to-body :close-on-click-modal="false">
      <div>
        <el-tabs type="border-card" class="auditStyle" @tab-click="handleTabClick" v-model="activeTab">
          <el-tab-pane name="toAudit">
            <span slot="label"><i class="el-icon-date"></i>待我审核</span>
            <div class="head-container">
              <el-input v-model="nickName" placeholder="请输入申请人" clearable size="small" prefix-icon="el-icon-search"
                style="margin-bottom: 20px" @input="handleSearch" />
            </div>
            <div class="show-frame-container">
              <template v-if="auditData.length > 0">
                <div class="show-frame" v-for="(item, index) in auditData" :key="index"
                  @click="borderTrigger(item, 'pending')">
                  <image-preview :src="item.avatar" :width="50" :height="50" />

                  <div class="plan-size">
                    <h4>{{ item.applicant }}提交的申请记录</h4>
                  </div>

                  <div class="singleHanded-css">
                    申请人：{{ item.applicant }}
                  </div>

                  <div class="planNumber-css" @click.stop="copyText(item.ordersNumber, '采购单号')">
                    采购单号：{{ item.ordersNumber }}
                  </div>

                  <div class="mannerName-css">
                    应付金额：{{ item.amountDue }}
                  </div>

                  <div class="paymentRequestCode-css" style="display: flex; align-items: center"
                    @click.stop="copyText(item.paymentRequestCode, '申请单号')">
                    申请单号：{{ item.paymentRequestCode }}
                  </div>

                  <div class="paymentAmount-css">
                    申请金额：
                    <h4 style="display: inline">
                      {{
                        item.payableAmount
                          ? item.payableAmount.toFixed(2)
                          : item.prepaymentAmount
                            ? item.prepaymentAmount.toFixed(2)
                            : item.returnAmount
                              ? item.returnAmount.toFixed(2)
                              : "0.00"
                      }}
                    </h4>
                    <dict-tag style="display: inline" :options="dict.type.request_payment_type"
                      :value="item.paymentType" />
                  </div>

                  <div class="shipTime-css">
                    {{ parseTime(item.applicationTime, "{y}-{m}-{d}") }}
                  </div>

                  <div class="planStatus-css" style="display: flex; align-items: center">
                    <dict-tag :options="dict.type.payment_review_status" :value="item.paymentReviewStatus" />
                    <el-button type="text" style="margin-left: 15px"
                      @click.stop="paymentRequestLog(item)">日志记录</el-button>
                  </div>
                </div>
              </template>
              <div v-else class="no-data">暂无数据。</div>
            </div>
          </el-tab-pane>
          <el-tab-pane name="audited" label="我已审核">
            <el-input v-model="nickNameReviewed" placeholder="请输入申请人" clearable size="small"
              prefix-icon="el-icon-search" style="margin-bottom: 20px" @input="handleSearch" />

            <div class="show-frame-container">
              <template v-if="planReviewed.length > 0">
                <div class="show-frame" v-for="(item, index) in planReviewed" :key="index">
                  <image-preview :src="item.avatar" :width="50" :height="50" />

                  <div class="plan-size">
                    <h4>{{ item.applicant }}提交的申请记录</h4>
                  </div>

                  <div class="singleHanded-css">
                    申请人：{{ item.applicant }}
                  </div>

                  <div class="planNumber-css" @click="copyText(item.ordersNumber, '采购单号')">
                    采购单号：{{ item.ordersNumber }}
                  </div>

                  <div class="mannerName-css">
                    应付金额：{{ item.amountDue }}
                  </div>

                  <div class="paymentRequestCode-css" style="display: flex; align-items: center"
                    @click="copyText(item.paymentRequestCode, '申请单号')">
                    申请单号：{{ item.paymentRequestCode }}
                  </div>

                  <div class="paymentAmount-css">
                    申请金额：
                    <h4 style="display: inline">
                      {{
                        item.payableAmount
                          ? item.payableAmount.toFixed(2)
                          : item.prepaymentAmount
                            ? item.prepaymentAmount.toFixed(2)
                            : item.returnAmount
                              ? item.returnAmount.toFixed(2)
                              : "0.00"
                      }}
                    </h4>
                    <dict-tag style="display: inline" :options="dict.type.request_payment_type"
                      :value="item.paymentType" />
                  </div>

                  <div class="shipTime-css" style="display: flex; align-items: center; gap: 5px">
                    <dict-tag :options="dict.type.payment_review_status" :value="item.paymentReviewStatus" />
                    <dict-tag v-if="item.paymentVoucherStatus !== '3'" :options="dict.type.payment_voucher_status"
                      :value="item.paymentVoucherStatus" />
                  </div>

                  <div class="planStatus-css" style="display: flex; align-items: center">
                    {{ parseTime(item.applicationTime, "{y}-{m}-{d}") }}
                    <el-button type="text" style="margin-left: 15px" @click="paymentRequestLog(item)">日志记录</el-button>
                  </div>
                </div>
              </template>
              <div v-else class="no-data">暂无数据。</div>
            </div>
          </el-tab-pane>
          <el-tab-pane name="myAudit" label="我发起的">
            <div class="show-frame-container">
              <template v-if="planInitiated.length > 0">
                <div class="show-frame" v-for="(item, index) in planInitiated" :key="index"
                  @click="borderTrigger(item, 'reviewed')">
                  <image-preview :src="item.avatar" :width="50" :height="50" />

                  <div class="plan-size">
                    <h4>{{ item.applicant }}提交的申请记录</h4>
                  </div>
                  <div class="singleHanded-css">
                    申请人：{{ item.applicant }}
                  </div>

                  <div class="planNumber-css" @click="copyText(item.ordersNumber, '采购单号')">
                    采购单号：{{ item.ordersNumber }}
                  </div>

                  <div class="mannerName-css">
                    应付金额：{{ item.amountDue }}
                  </div>

                  <div class="paymentRequestCode-css" @click="copyText(item.paymentRequestCode, '申请单号')">
                    申请单号：{{ item.paymentRequestCode }}
                  </div>

                  <div class="paymentAmount-css">
                    申请金额：
                    <h4 style="display: inline">
                      {{
                        item.payableAmount
                          ? item.payableAmount.toFixed(2)
                          : item.prepaymentAmount
                            ? item.prepaymentAmount.toFixed(2)
                            : item.returnAmount
                              ? item.returnAmount.toFixed(2)
                              : "0.00"
                      }}
                    </h4>
                    <dict-tag style="display: inline" :options="dict.type.request_payment_type"
                      :value="item.paymentType" />
                  </div>

                  <div class="shipTime-css" style="display: flex; align-items: center; gap: 5px">
                    <dict-tag :options="dict.type.payment_review_status" :value="item.paymentReviewStatus" />
                    <dict-tag v-if="item.paymentVoucherStatus !== '3'" :options="dict.type.payment_voucher_status"
                      :value="item.paymentVoucherStatus" />
                  </div>

                  <div class="planStatus-css" style="display: flex; align-items: center">
                    {{ parseTime(item.applicationTime, "{y}-{m}-{d}") }}
                    <el-button type="text" style="margin-left: 15px"
                      @click.native.stop="paymentRequestLog(item)">日志记录</el-button>
                  </div>
                </div>
              </template>
              <div v-else class="no-data">暂无数据。</div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      <pagination v-show="logTotals > 0" :total="logTotals" :page.sync="auditQueryParams.pageNum"
        :limit.sync="auditQueryParams.pageSize" @pagination="handlePagination" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelTreat">取 消</el-button>
      </div>
    </el-dialog>

    <el-drawer title="详情" :visible.sync="drawer">
      <div class="drawerValueUserImg">
        <image-preview :src="this.drawerValue.avatar" :width="50" :height="50" />
      </div>
      <div class="drawerValueSingleHanded">
        <h3>{{ this.drawerValue.applicant }}提交的申请记录</h3>
      </div>
      <div class="drawerValuePlanStatus">
        <dict-tag :options="dict.type.payment_review_status" :value="this.drawerValue.paymentReviewStatus" />
      </div>
      <el-descriptions class="margin-top" :column="2" direction="vertical">
        <el-descriptions-item label="采购单号" :span="2"><span style="color: black">{{
          this.drawerValue.ordersNumber
            }}</span></el-descriptions-item>
        <el-descriptions-item label="申请人"><span style="color: black">{{
          this.drawerValue.applicant
            }}</span></el-descriptions-item>
        <el-descriptions-item label="申请类型">
          <span style="color: black">
            <dict-tag :options="dict.type.request_payment_type" :value="this.drawerValue.paymentType" />
          </span></el-descriptions-item>
        <el-descriptions-item label="应付金额">
          <span style="color: black">{{
            this.drawerValue.amountDue
          }}</span></el-descriptions-item>
        <el-descriptions-item label="申请金额">
          <span style="color: black; font-weight: bold">
            {{
              this.drawerValue.payableAmount
                ? this.drawerValue.payableAmount.toFixed(2)
                : this.drawerValue.prepaymentAmount
                  ? this.drawerValue.prepaymentAmount.toFixed(2)
                  : this.drawerValue.returnAmount
                    ? this.drawerValue.returnAmount.toFixed(2)
                    : "0.00"
            }}
          </span>
        </el-descriptions-item>
      </el-descriptions>
      <div v-if="
        this.drawerValue.items &&
        this.drawerValue.items.length > 0 &&
        this.drawerValue.items.some((item) => item && item.sku)
      " class="items-container">
        <h4>商品明细</h4>
        <el-table :data="this.drawerValue.items.filter((item) => item && item.sku)" stripe style="width: 100%">
          <el-table-column prop="sku" label="SKU" width="150"></el-table-column>
          <el-table-column prop="productName" label="商品名称"></el-table-column>
          <el-table-column prop="quantity" label="数量" width="50"></el-table-column>
        </el-table>
      </div>
      <hr />
      <div>
        <div>
          <image-preview :src="this.drawerValue.avatar" :width="50" :height="50" />
          <div class="sponsor">发起人</div>
          <div class="sponsor-name">{{ this.drawerValue.applicant }}</div>
          <div class="sponsor-time">
            {{ parseTime(this.drawerValue.applicationTime, "{y}-{m}-{d}") }}
            {{ parseTime(this.drawerValue.applicationTime, "{h}:{i}") }}
          </div>
        </div>
        <div></div>
      </div>
      <div class="_scroll-container">
        <div v-for="(item, index) in PaymentRequestProcessData" :key="index"
          :class="index === 0 ? '' : 'postUserDept-css'">
          <image-preview :src="item.avatar" :width="50" :height="50" />
          <div class="sponsor">审批人</div>
          <div class="sponsor-name">
            {{ item.nickName }}
            <span v-if="item" v-show="item.processStatus == 0 || item.processStatus == null">
              (审核中)
            </span>
            <span v-if="item" v-show="item.processStatus == 1">
              (同意)&nbsp;&nbsp;{{ item.processTime }}
            </span>
            <span v-if="item" v-show="item.processStatus == 2"> (拒绝) </span>
          </div>
          <div class="sponsor-time">
            {{ item.deptName }}
          </div>
          <div class="postUserDept-postName">
            {{ item.roleName }}
          </div>
        </div>
      </div>
      <div class="approval" v-if="isNeedReview">
        <el-input v-model="processRemark" type="textarea" class="processRemark-input" placeholder="备注填写"
          rows="3"></el-input>
        <div class="button-group">
          <el-button @click="rejectRequest(drawerValue.paymentRequestId, 2)" type="danger">拒 绝</el-button>
          <el-button type="primary" @click="approveRequest(drawerValue.paymentRequestId, 1)">同 意</el-button>
        </div>
      </div>
    </el-drawer>

    <!-- 审核日志记录 -->
    <el-dialog :visible.sync="openLog" width="1400px" append-to-body :close-on-click-modal="false">
      <el-table v-loading="loading" :data="PaymentRequestLogList" height="500px">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="采购订单号" align="center" prop="ordersNumber" />
        <el-table-column label="审核状态" align="center" prop="logStatus">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.process_status" :value="scope.row.logStatus" />
          </template>
        </el-table-column>
        <el-table-column label="审核人" align="center" prop="logApplicant" />
        <el-table-column label="审核时间" align="center" prop="logTime" />
        <el-table-column label="审核备注" align="center" prop="logRemark" />
        <el-table-column label="申请人" align="center" prop="applicant" />
        <el-table-column label="申请时间" align="center" prop="applicationTime" />
      </el-table>

      <pagination v-show="logTotals > 0" :total="logTotals" :page.sync="logParam.pageNum"
        :limit.sync="logParam.pageSize" @pagination="getPaymentRequestLogList" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelRequestLog">取消</el-button>
      </div>
    </el-dialog>

    <!-- 退款弹窗 -->
    <el-dialog title="采购订单申请退款" :visible.sync="returnDialogVisible" width="700px">
      <div class="return-form">
        <el-form ref="returnForm" :model="returnForm" label-width="100px">
          <el-form-item label="采购编号">
            <span>{{ currentOrder.ordersNumber }}</span>
          </el-form-item>

          <el-form-item label="退款方式" prop="paymentType">
            <el-radio-group v-model="returnForm.paymentType" @change="handlePaymentType">
              <el-radio label="2">仅退款</el-radio>
              <el-radio label="3">退货退款</el-radio>
              <el-radio label="4">换货</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="SKU选择">
            <div class="sku-list">
              <div v-for="(item, index) in ordersProductList" :key="index" class="sku-item">
                <el-checkbox v-model="item.selected" @change="handleSkuSelect(item)">
                  {{ item.sku }} - {{ item.productName }}
                </el-checkbox>
              </div>
            </div>
          </el-form-item>

          <!-- 选中的SKU详情表单 -->
          <div v-if="selectedSkus.length > 0" class="selected-skus">
            <h3>已选择的SKU</h3>

            <div v-for="item in selectedSkus" :key="item.sku" class="selected-sku-item">
              <div class="sku-header">
                <span class="sku-title">{{ item.sku }} - {{ item.productName }}</span>
              </div>

              <el-form-item :label="'数量'" style="margin-top: 10px">
                <el-input v-model="item.quantity" style="width: 210px" placeholder="退款数量">
                </el-input>&nbsp;<span :title="spanTitle">{{ spanTitle }}</span>{{ getLimitQty(item) }}
              </el-form-item>
              <!-- 金额显示  -->
              <el-form-item label="单价金额" style="margin-top: 10px">
                <el-input v-model="item.currentAmount" style="width: 210px" @input="calculateTotalAmount"  placeholder="手动输入金额"/>
                &nbsp;<span>单价：¥{{ item.amount }}</span>
                <!-- <el-button type="text" size="mini" @click="autoCalculateItemAmount(item)">
                  自动计算
                </el-button> -->
              </el-form-item>

              <!-- 运费输入框 - 每个商品都有，非必填 -->
              <el-form-item label="运费" style="margin-top: 10px">
                <el-input v-model="item.freight" placeholder="请输入运费（选填）" style="width: 210px"
                  @input="calculateTotalAmount" />
              </el-form-item>
              <el-divider></el-divider>
            </div>
          </div>

          <!-- 总退款金额和备注 -->
          <el-form-item label="退款金额">
            <el-input v-model="returnForm.returnAmount" placeholder="总退款金额" disabled style="width: 210px"></el-input>
            &nbsp;<span>最大可退款金额：{{ maxRefundAmount }}</span>
          </el-form-item>

          <el-form-item label="退款备注">
            <el-input v-model="returnForm.returnRemark" type="textarea" :rows="3" placeholder="请输入退款备注">
            </el-input>
          </el-form-item>
        </el-form>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="returnDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitFormReturn">确认提交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  listProcuredOrders,
  getProcuredOrders,
  updateProcuredOrders,
  getUpdateInboundNumber,
  updateExpressNumber,
  getProcuredOrderAmountDueById,
  addPaymentRequestQuash,
  selectPaymentRequestList,
  setCancelPaymentRequestByIds,
  addBatchPaymentRequestQuash,
  selectPaymentRequestByStatus,
  getPaymentRequestProcessList,
  updateProcessStatus,
  selectPaymentRequestLogList,
  getOrdersProductList, //查询该申请的采购订单数据（商品信息，入库，出库信息）
  addPaymentReturnQuash, //申请退款
  revokeProcuredOrders,
  setSolvePaymentRequestByIds, //标记处理
} from "@/api/orders/ProcuredOrders";
import {
  getSelectVendorTreeList,
  getSelectCompanyTreeList,
  getSelectPreWarehouseTreeList,
  getSelectMonetaryTreeList,
} from "@/api/procured/plan";
import { getVendor } from "@/api/commodity/vendor";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import store from "@/store";
import { formatPath } from "@/api/utils/pathUtils";
export default {
  name: "ProcuredOrders",
  dicts: [
    "inbound_status",
    "payment_status",
    "request_payment_type",
    "request_payment_status",
    "payment_review_status",
    "tb_plan",
    "sys_job_status",
    "process_status",
    "payment_voucher_status",
    "tb_delete_status",
    "payment_return_status",
    "procured_orders_status",
  ],
  components: {
    Treeselect,
    TooltipCell: {
      name: "TooltipCell",
      functional: true, // 采用函数式组件更轻量
      props: {
        value: {
          type: [String, Number],
          default: null,
        },
      },
      render(h, ctx) {
        // 当 value 为 null/undefined/空值时显示 '-'，否则转成字符串
        const val =
          ctx.props.value != null && ctx.props.value !== ""
            ? String(ctx.props.value)
            : "-";
        return h(
          "el-tooltip",
          {
            props: {
              content: val,
              placement: "top",
              disabled: !(ctx.props.value != null && ctx.props.value !== ""),
            },
          },
          [h("span", val)]
        );
      },
    },
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      id: [],
      // 子表选中数据
      checkedOrdersProduct: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 总条数
      totals: 0,
      // 采购订单表格数据
      ProcuredOrdersList: [],
      // 采购订单商品表格数据
      ordersProductList: [],
      // 弹出层标题
      title: "",
      titleAdvance: "",
      titleRequest: "",
      titleTrace: "",
      titleQuash: "",
      // 是否显示弹出层
      open: false,
      openAdvance: false,
      openRequest: false,
      openTrace: false,
      openQuash: false,
      dialogVisible: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ordersNumber: null,
        planId: null,
        searchType: "1",
        searchContent: null,
        paymentStatus: null,
        returnStatus: null,
        searchInboundStatus: null,
        status: null,
        deleteStatus: "0",
      },
      // 表单参数
      form: {},
      formTrace: {},
      // 供应商
      vendorOptions: [],
      // 机构管理里
      companyOptions: [],
      // 仓库列表
      warehouseOptions: [],
      //货币单位
      monetaryOptions: [],
      activeName: "first",

      //申请预付款表单参数
      formAdvance: {},
      //申请记录
      // 查询参数
      queryParam: {
        pageNum: 1,
        pageSize: 10,
        paymentType: null,
        paymentStatus: null,
        paymentReviewStatus: null,
        procuredOrderId: null,
      },
      // 申请预付款表格数据
      RequestAdvanceList: [],
      //最大可申请钱
      totalAmountDue: null,
      disableButton: false, // 初始状态为可用
      select: "1",
      // 应付款
      formQuash: {
        paymentType: "0", // 付款方式
        prepaymentCycle: "", // 付款周期
        prepaymentAmount: "", // 预付金额
        otherFeeAmount: "", // 其他费用金额
        otherFeeType: "", // 其他费用类型
        otherFeeRemark: "", // 备注
      },
      rules: {},
      // 申请付款表格数据
      PaymentRequestList: [],
      batchOrderNumbers: [], // 勾选订单的编号

      //审核提示
      audit: "",
      //审核弹出框
      openAudit: false,
      // 查询参数
      auditQueryParams: {
        pageNum: 1,
        pageSize: 10,
        reviewStatus: null,
      },
      //存储审核中的数据
      auditData: [],
      auditLength: null,
      drawer: false,
      drawerValue: {},
      //当前用户id
      userId: store.getters.userId,
      //当前用户所在的部门id
      deptId: store.getters.deptId,
      //获得已审批的数据
      planReviewed: [],
      //获得已审批的数据条数
      planReviewedLength: null,
      //获得我发起的审批数据
      planInitiated: [],
      //获得我发起的审批数据条数
      planInitiatedLength: null,
      nickName: null,
      nickNameReviewed: null,
      activeTab: "toAudit",
      tabTypeMap: {
        toAudit: 0,
        audited: 1,
        myAudit: 2,
      },
      PaymentRequestProcessData: [],
      PaymentRequestProcessLength: null,
      PymentRequestProcessParams: {
        pageNum: 1,
        pageSize: 10,
        paymentRequestId: "",
        processStatus: "",
        reviewerId: "",
        processRemark: "",
      },
      processRemark: "",
      openLog: false,
      PaymentRequestLogList: [],
      // 查询参数
      logParam: {
        pageNum: 1,
        pageSize: 10,
      },
      logTotals: 0,
      isSubmitting: false,
      selection: [],
      isNeedReview: true,

      //申请退款
      returnDialogVisible: false,
      currentOrder: {},
      selectedSkus: [],
      returnForm: {
        orderNo: "",
        paymentType: "3", // 默认为退货退款
        returnAmount: "",
        returnRemark: "",
        returnItems: [],
      },
      //最大可退款金额
      maxRefundAmount: null,

      highlightOrderNumbers: [], // 需要高亮的订单号列表
      showHighlightTip: false, // 是否显示高亮提示

      spanTitle: "最大退款库存数量：", //显示名称
      isManualRefundAmount: false, // 是否手动输入退款金额
    };
  },

  created() {
    // 检查是否有需要高亮的订单号
    const highlightOrders = this.$route.query.highlightOrders;
    const fromSales = this.$route.query.fromSales;

    if (highlightOrders && fromSales) {
      this.highlightOrderNumbers = highlightOrders.split(",");
      this.showHighlightTip = true;
    }
    this.getList();
    this.getVendor();
    this.getCompany();
    this.getPreWarehouse();
    this.getMonetary();
    this.rules = {
      paymentType: [
        { required: true, message: "请选择付款方式", trigger: "change" },
      ],
      prepaymentCycle: [
        {
          required: true,
          message: "请选择付款周期",
          trigger: "change",
          validator: (rule, value, callback) => {
            if (this.formQuash.paymentType === "0" && !value) {
              callback(new Error("请选择付款周期"));
            } else {
              callback();
            }
          },
        },
      ],
      prepaymentAmount: [
        {
          required: true,
          trigger: "change",
          validator: this.validatePrepaymentAmount,
        },
      ],
      otherFeeAmount: [
        {
          validator: this.validateOtherFeeAmount,
          trigger: "blur",
        },
      ],
      otherFeeRemark: [
        {
          validator: this.validateOtherFeeRemark,
          trigger: "blur",
        },
      ],
    };
    // 处理完后立即清空URL参数
    if (highlightOrders || fromSales) {
      this.$nextTick(() => {
        this.$router.replace({
          path: this.$route.path,
          query: {},
        });
      });
    }
  },
  computed: {
    // calculateTotalAmount() {
    //   return this.ordersProductList
    //     .reduce((total, item) => {
    //       // 确保是数字，如果为空或非数字则视为0
    //       const amount = parseFloat(item.amount) || 0;
    //       return total + amount;
    //     }, 0)
    //     .toFixed(2);
    // },
    // totalAmount() {
    //   return (
    //     Number(this.form.amountDue) +
    //     Number(this.form.freight) / Number(this.form.currency) -
    //     Number(this.form.discountAmount)
    //   );
    // },
    skuNumberSums() {
      const sums = {};
      // 遍历表格列表数据，根据 sku 进行数量累加
      this.ordersProductList.forEach((item) => {
        const { sku, transferableNumber } = item;
        if (!sums[sku]) {
          sums[sku] = 0;
        }
        // number 可能是字符串，这里转成数字再相加
        sums[sku] += Number(transferableNumber) || 0;
      });
      return sums;
    },
    // 根据 SKU 分组，返回 { sku: { start, count } } 形式
    skuGroups() {
      const groups = {};
      this.ordersProductList.forEach((item, index) => {
        const key = item.sku;
        if (key) {
          if (!groups[key]) {
            groups[key] = { start: index, count: 1 };
          } else {
            groups[key].count += 1;
          }
        }
      });
      return groups;
    },
    // 按 SKU 汇总各组的金额、税额、含税金额、总成本与数量（这里字段名称对照实际表格数据）
    skuAggregates() {
      const result = {};
      Object.entries(this.skuGroups).forEach(([sku, { start, count }]) => {
        let aggregateQuantity = 0;
        let aggregatedAmount = 0;
        let aggregatedFreight = 0;
        for (let idx = start; idx < start + count; idx++) {
          const item = this.ordersProductList[idx];
          // 累加数量，注意字段名称：transferableNumber 或其它
          aggregateQuantity += Number(item.transferableNumber) || 0;
          // 金额 = 单价 * 汇率 * 数量（假设 productPrice 为单价，currency 为汇率）
          const unitPrice = Number(item.productPrice) || 0;
          const exchangeRate = Number(item.currency) || 1;
          aggregatedAmount +=
            unitPrice * (Number(item.transferableNumber) || 0) * exchangeRate;
          // 运费累计
          aggregatedFreight += Number(item.freight) || 0;
        }
        // 取第一行数据，假设同一 SKU 内税率一致，可取第一行的 rate 字段
        const primary = this.ordersProductList[start];
        const rate = Number(primary.rate) || 0;
        console.log("计算属性中的税率", JSON.stringify(primary.rate, null, 2));
        // 税额：金额 * 税率 / 100
        const aggregatedTax = (aggregatedAmount * rate) / 100;
        console.log("计算属性中的税额", JSON.stringify(aggregatedTax, null, 2));
        // 含税金额
        const aggregatedTaxIncluded = aggregatedAmount + aggregatedTax;
        console.log(
          "计算属性中的含税金额",
          JSON.stringify(aggregatedTaxIncluded, null, 2)
        );
        // 总成本：含税金额 + 运费
        const aggregatedTotalCost = aggregatedTaxIncluded + aggregatedFreight;
        console.log(
          "计算属性中的总成本",
          JSON.stringify(aggregatedTotalCost, null, 2)
        );
        result[sku] = {
          // 汇总的金额数据
          amountSum: aggregatedAmount,
          taxSum: aggregatedTax,
          taxIncludedSum: aggregatedTaxIncluded,
          totalCostSum: aggregatedTotalCost,
          quantity: aggregateQuantity,
        };
      });
      return result;
    },
    totalCost() {
      if (!this.ordersProductList || !Array.isArray(this.ordersProductList)) {
        return 0; // 或者返回适当的默认值
      }
      return this.ordersProductList.reduce((total, product) => {
        const taxIncluded = Number(product.taxIncluded) || 0;
        const freight = Number(product.freight) || 0;
        return total + taxIncluded + freight;
      }, 0);
    },
  },
  methods: {
    /** 查询采购订单列表 */
    getList() {
      this.loading = true;
      const value = this.queryParams.statusFilter;
      if (value) {
        if (value.startsWith("pay-")) {
          this.queryParams.paymentStatus = value.replace("pay-", "");
          this.queryParams.returnStatus = null;
        } else if (value.startsWith("return-")) {
          this.queryParams.returnStatus = value.replace("return-", "");
          this.queryParams.paymentStatus = null;
        }
      } else {
        this.queryParams.paymentStatus = null;
        this.queryParams.returnStatus = null;
      }

      const ordervalue = this.queryParams.orderStatusFilter;
      if (ordervalue) {
        if (ordervalue.startsWith("orders-")) {
          this.queryParams.status = ordervalue.replace("orders-", "");
          this.queryParams.deleteStatus = null;
        } else if (ordervalue.startsWith("delete-")) {
          this.queryParams.deleteStatus = ordervalue.replace("delete-", "");
          this.queryParams.status = null;
        }
      } else {
        this.queryParams.status = null;
        this.queryParams.deleteStatus = "0";
      }
      listProcuredOrders(this.queryParams).then((response) => {
        this.ProcuredOrdersList = response.rows;
        // for (let i = 0; i < this.ProcuredOrdersList.length; i++) {
        //   const ordersId = this.ProcuredOrdersList[i].ordersId;
        //   //先注释了不知道干嘛用的
        //   //getUpdateInboundNumber(ordersId);
        // }
        this.total = response.total;
        this.loading = false;
        // 如果有需要高亮的订单，执行高亮逻辑
        if (this.highlightOrderNumbers.length > 0) {
          this.$nextTick(() => {
            this.highlightTargetOrders();
            this.highlightOrderNumbers = []; // 清空避免递归
          });
        }
      });
    },
    // 新增：高亮目标订单的方法
    highlightTargetOrders() {
      this.queryParams.ordersNumberList = this.highlightOrderNumbers;
      this.getList();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        ordersId: null,
        ordersNumber: null,
        ordersNumberList: null,
        planId: null,
        expressNumber: null,
        total: null,
        approver: null,
        approvedTime: null,
        amountDue: null,
        inboundStatus: null,
        inboundNumber: null,
        paymentStatus: null,
        deleteStatus: null,
        addTime: null,
        updateTime: null,
      };
      this.formAdvance = {
        requestAmount: null,
        paymentDate: new Date(),
        requestRemark: null,
      };
      this.formTrace = {
        arriveDate: null,
        expressNumber: null,
        expressRemark: null,
        ordersId: null,
      };
      this.ordersProductList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.searchContent = null;
      this.queryParams.ordersNumberList = null; // 清空销售计划提前结束跳转过来的参数
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.ordersId);
      this.id = selection.map((item) => item.paymentRequestId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
      this.batchOrderNumbers = selection.map((item) => item.ordersNumber);
      this.selection = selection;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const ordersId = row.ordersId || this.ids;
      getProcuredOrders(ordersId).then((response) => {
        this.form = response.data;
        this.ordersProductList = response.data.ordersProductList;
        this.open = true;
        this.title = "采购订单详情";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.ordersProductList = this.ordersProductList;
          if (this.form.ordersId != null) {
            updateProcuredOrders(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 采购订单商品添加按钮操作 */
    handleAddOrdersProduct() {
      let obj = {};
      obj.proNo = "";
      obj.productName = "";
      obj.productPrice = "";
      obj.transferableNumber = "";
      obj.amount = "";
      obj.storageNumber = "";
      obj.productRemark = "";
      obj.deleteStatus = "";
      this.ordersProductList.push(obj);
    },
    /** 复选框选中数据 */
    handleOrdersProductSelectionChange(selection) {
      this.checkedOrdersProduct = selection.map((item) => item.index);
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "product/ProcuredOrders/export",
        {
          ...this.queryParams,
        },
        `ProcuredOrders_${new Date().getTime()}.xlsx`
      );
    },
    /** 查询供应商的下拉数据结果 */
    getVendor() {
      getSelectVendorTreeList().then((response) => {
        this.vendorOptions = response.data;
      });
    },
    /** 查询机构管理下拉数据结果 */
    getCompany() {
      getSelectCompanyTreeList().then((response) => {
        this.companyOptions = response.data;
      });
    },

    /** 查询仓库 */
    getPreWarehouse() {
      getSelectPreWarehouseTreeList().then((response) => {
        this.warehouseOptions = response.data;
      });
    },

    /** 货币单位 */
    getMonetary() {
      getSelectMonetaryTreeList().then((response) => {
        this.monetaryOptions = response.data;
      });
    },
    autoFillModelVendorId(row) {
      if (row != null) {
        getVendor(row).then((response) => {
          this.form.contract = response.data.contract;
        });
        this.form.contract = null;
      }
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleUpdate":
          this.handleUpdate(row);
          break;
        case "handleQuash":
          this.handleQuash(row);
          break;
        case "handleReturn":
          this.handleReturn(row);
          break;
        case "handleCancel":
          this.handleCancel(row);
        default:
          break;
      }
    },
    /** 申请付款按钮操作 */
    handleQuash(row) {
      this.reset();
      const ordersId = row.ordersId || this.ids;
      getProcuredOrders(ordersId).then((response) => {
        this.formQuash = response.data;
        this.titleQuash = "采购订单申请付款";
        this.openQuash = true;
      });
      getProcuredOrderAmountDueById(row.ordersId).then((response) => {
        this.totalAmountDue = response.totalAmountDue;
      });
    },
    /** 申请付款确定按钮 */
    async submitFormQuash() {
      // 避免重复提交
      if (this.isSubmitting) return;

      // 表单验证
      const valid = await new Promise((resolve) => {
        this.$refs.formQuash.validate((isValid) => {
          resolve(isValid);
        });
      });

      if (!valid) return; // 如果验证不通过，则直接退出
      let originalPath = this.$route.path; // 当前路径
      let componentPath = formatPath(originalPath);
      try {
        // 执行提交操作
        await addPaymentRequestQuash(
          this.formQuash,
          componentPath,
          this.formQuash.ordersId
        );
        this.getList();
        this.$modal.msgSuccess("申请付款成功！");
        this.openQuash = false; // 关闭对话框
      } catch (error) {
        this.$modal.msgError("提交审请付款中，请勿重复提交");
      } finally {
        this.isSubmitting = false; // 请求完成后解锁
      }
    },
    /** 申请付款取消按钮 */
    cancelQuash() {
      this.openQuash = false;
      this.$nextTick(() => {
        if (this.$refs.formQuash) {
          this.$refs.formQuash.resetFields();
        }
      });
    },
    //查看申请记录
    applicationRecords(row) {
      this.titleRequest = row.ordersNumber + "申请记录";
      this.openRequest = true;
      this.queryParam.procuredOrderId = row.ordersId;
      this.getPaymentRequestList();
    },
    //查询所有的申请记录
    getPaymentRequestList() {
      this.loading = true;
      selectPaymentRequestList(this.queryParam).then((response) => {
        this.PaymentRequestList = response.rows;
        this.totals = response.total;
        this.loading = false;
      });
    },
    handleQueryRequest() {
      this.queryParam.pageNum = 1;
      this.getPaymentRequestList();
    },
    //申请记录里面的重置按钮
    resetQueryRequest() {
      this.resetForm("queryForm");
      this.handleQueryRequest();
    },
    cancelRequest() {
      this.openRequest = false;
      this.reset();
    },
    //取消申请
    handleRequest(row) {
      const paymentRequestIds = row.paymentRequestId || this.id;
      this.$modal
        .confirm("您确定取消此记录吗？")
        .then(function () {
          return setCancelPaymentRequestByIds(paymentRequestIds);
        })
        .then(() => {
          this.getPaymentRequestList();
          this.$modal.msgSuccess("申请取消成功！");
        })
        .catch(() => { });
    },
    //驳回标记处理
    handleRequestSolve(row) {
      const paymentRequestId = row.paymentRequestId;
      setSolvePaymentRequestByIds(paymentRequestId)
        .then(() => {
          this.getPaymentRequestList();
          this.$modal.msgSuccess("标记处理成功");
        })
        .catch(() => { });
    },
    autoFillModel() {
      if (this.formAdvance.prepaymentAmount > this.totalAmountDue) {
        this.disableButton = true;
      } else {
        this.disableButton = false;
      }
    },
    /** 跟踪记录 */
    handleTrace(row) {
      this.titleTrace = "跟踪记录";
      this.openTrace = true;
      this.formTrace.ordersId = row.ordersId;
    },

    cancelTrace() {
      this.openTrace = false;
      this.reset();
    },
    submitFormTrace() {
      this.$refs["formTrace"].validate((valid) => {
        if (valid) {
          updateExpressNumber(this.formTrace).then((response) => {
            this.$modal.msgSuccess("新增成功");
            this.openTrace = false;
            this.getList();
            this.reset();
          });
        }
      });
    },
    handlePaymentTypeChange() {
      this.resetFormFields();
    },
    resetFormFields() {
      // 如果使用了表单验证，清除验证状态
      this.$nextTick(() => {
        this.$refs["formQuash"].clearValidate();
      });
    },

    // 自定义验证函数
    validateOtherFeeAmount(rule, value, callback) {
      const type = this.formQuash.otherFeeType;
      if (type === "增加" || type === "减少") {
        if (!value) {
          callback(new Error("请输入金额"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    },
    validateOtherFeeRemark(rule, value, callback) {
      const type = this.formQuash.otherFeeType;
      if (type === "增加" || type === "减少") {
        if (!value) {
          callback(new Error("请输入备注"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    },
    validatePrepaymentAmount(rule, value, callback) {
      const prepaymentAmount = Number(this.formQuash.prepaymentAmount);
      const totalAmountDue = Number(this.totalAmountDue);
      if (this.formQuash.paymentType === "0") {
        if (!value) {
          callback(new Error("请输入预付金额"));
        } else if (prepaymentAmount > totalAmountDue) {
          callback(new Error(" "));
        } else {
          callback();
        }
      } else {
        callback();
      }
    },
    // 处理其他费用类型改变的事件
    handleOtherFeeTypeChange(value) {
      if (value === "") {
        // 清空金额和备注字段
        this.formQuash.otherFeeAmount = "";
        this.formQuash.otherFeeRemark = "";
        // 清除金额和备注字段的验证状态
        this.$nextTick(() => {
          this.$refs["formQuash"].clearValidate([
            "otherFeeAmount",
            "otherFeeRemark",
          ]);
        });
      }
    },

    /** 新增按钮操作 */
    handleAddBatch() {
      if (!this.selection || this.selection.length === 0) {
        this.$message.warning("请先勾选订单");
        return;
      }
      const validList = this.selection.every(
        (item) => Number(item.deleteStatus) === 0
      );
      if (!validList) {
        this.$message.warning("请选择订单状态为【正常】");
        return;
      }
      this.dialogVisible = true;
    },
    // 批量申请付款的逻辑处理
    handleConfirm() {
      let originalPath = this.$route.path; // 当前路径
      let componentPath = formatPath(originalPath);
      addBatchPaymentRequestQuash(this.ids, componentPath).then((response) => {
        this.dialogVisible = false;
        this.$message({
          message: "批量申请付款成功",
          type: "success",
        });
      });
    },

    //弹出审核中
    underReview() {
      this.openAudit = true;
      this.audit = "审批管理";
      this.getAuditList(0);
    },
    getAuditList(type) {
      this.auditQueryParams.reviewStatus = type;
      this.auditQueryParams.userId = this.userId;

      // 设置搜索人
      if (type === 0) {
        this.auditQueryParams.applicant = this.nickName;
      } else if (type === 1) {
        this.auditQueryParams.applicant = this.nickNameReviewed;
      } else {
        this.auditQueryParams.applicant = null;
      }

      selectPaymentRequestByStatus(this.auditQueryParams).then((res) => {
        if (type === 0) {
          this.auditData = res.rows || [];
          this.auditLength = this.auditData.length;
          this.logTotals = res.total;
        } else if (type === 1) {
          this.planReviewed = res.rows || [];
          this.planReviewedLength = this.planReviewed.length;
          this.logTotals = res.total;
        } else if (type === 2) {
          this.planInitiated = res.rows || [];
          this.planInitiatedLength = this.planInitiated.length;
          this.logTotals = res.total;
        }
      });
    },
    cancelTreat() {
      this.openAudit = false;
    },
    handleTabClick(tab) {
      const type = this.tabTypeMap[tab.name];
      if (type !== undefined) {
        this.getAuditList(type);
      }
    },
    handlePagination() {
      const type = this.tabTypeMap[this.activeTab];
      if (type !== undefined) {
        this.getAuditList(type);
      }
    },
    handleSearch() {
      this.auditQueryParams.pageNum = 1;
      this.getAuditList(this.tabTypeMap[this.activeTab]);
    },
    borderTrigger(data, source) {
      this.drawer = true;
      this.drawerValue = data;
      this.isNeedReview = source === "pending"; // 根据来源确定是否显示审核按钮
      getPaymentRequestProcessList(data.paymentRequestId).then((r) => {
        this.PaymentRequestProcessLength = r.data.length;
        this.PaymentRequestProcessData = r.data;
      });
    },
    /** 审批同意按钮 */
    async approveRequest(paymentRequestId, processStatus) {
      // 避免重复提交
      if (this.isSubmitting) return;

      this.PymentRequestProcessParams.paymentRequestId = paymentRequestId;
      this.PymentRequestProcessParams.processStatus = processStatus;
      this.PymentRequestProcessParams.reviewerId = this.userId;
      this.PymentRequestProcessParams.processRemark = this.processRemark;

      try {
        // 执行提交操作
        await updateProcessStatus(this.PymentRequestProcessParams);
        let title = "同意审批";
        if (processStatus != 1) {
          title = "拒绝审批";
        }
        this.$modal.msgSuccess(title);
        this.PymentRequestProcessParams.paymentRequestId = null;
        this.PymentRequestProcessParams.processStatus = null;
        this.PymentRequestProcessParams.reviewerId = null;
        this.PymentRequestProcessParams.processRemark = null;
        this.processRemark = null;
        this.drawer = false;
        this.getAuditList(0);
        this.getList();
      } catch (error) {
        this.$modal.msgError("提交审批中，请勿重复提交");
      } finally {
        this.isSubmitting = false; // 请求完成后解锁
      }
    },
    /** 审批拒绝按钮 */
    rejectRequest(paymentRequestId, processStatus) {
      if (!this.processRemark) {
        this.$message.error("请填写备注");
        return;
      }
      this.approveRequest(paymentRequestId, processStatus);
    },
    //查审核日志
    paymentRequestLog(row) {
      this.openLog = true;
      this.logParam.paymentRequestId = row.paymentRequestId;
      this.getPaymentRequestLogList();
    },
    //查询所有的申请记录
    getPaymentRequestLogList() {
      this.loading = true;
      selectPaymentRequestLogList(this.logParam).then((response) => {
        this.PaymentRequestLogList = response.rows;
        this.logTotals = response.rows.length;
        this.loading = false;
      });
    },
    cancelRequestLog() {
      this.openLog = false;
      this.reset();
    },
    async copyText(val, title) {
      try {
        // 复制文本到剪贴板
        await navigator.clipboard.writeText(val);
        // 显示复制成功的消息
        this.$modal.msgSuccess(title + "已复制！");
      } catch (error) {
        // 复制失败的处理
        console.error("复制失败:", error);
        this.$modal.msgError("复制失败，请重试！");
      }
    },
    downloadImage(path) {
      const fullUrl = process.env.VUE_APP_BASE_API + path;
      const fileName = path.substring(path.lastIndexOf("/") + 1);
      const link = document.createElement("a");
      link.href = fullUrl;
      link.setAttribute("download", fileName);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },

    // 判断当前行是否为分组中第一行（基于某个字段，比如 sku）
    isFirstRowInGroup(row, field) {
      const firstIndex = this.ordersProductList.findIndex(
        (item) => item[field] === row[field]
      );
      return this.ordersProductList.indexOf(row) === firstIndex;
    },

    spanMethod({ row, column, rowIndex }) {
      // 不合并 GTIN、数量、运费这几列
      if (["gtin", "transferableNumber", "freight"].includes(column.property)) {
        return { rowspan: 1, colspan: 1 };
      }

      // 基于 SKU 分组的合并逻辑
      const currentSku = row.sku;
      const firstIndex = this.ordersProductList.findIndex(
        (item) => item.sku === currentSku
      );
      if (rowIndex === firstIndex) {
        const rowspan = this.ordersProductList.filter(
          (item) => item.sku === currentSku
        ).length;
        return { rowspan, colspan: 1 };
      }

      return { rowspan: 0, colspan: 0 };
    },

    /////////////////////////////////////////////////退款开始/////////////////////////////////////////////////
    /** 申请退款按钮操作 */
    handleReturn(row) {
      this.currentOrder = row;
      this.$set(this, "selectedSkus", []);
      this.isManualRefundAmount = false
      // 2. 重置表单
      this.returnForm = {
        orderNo: row.ordersNumber,
        paymentType: "3",
        returnAmount: "",
        returnRemark: "",
      };

      // 3. 重置所有商品的选中状态(这一步很关键)
      if (this.ordersProductList) {
        this.ordersProductList.forEach((item) => {
          this.$set(item, "selected", false);
        });
      }
      const ordersId = row.ordersId || this.ids;
      getOrdersProductList(ordersId).then((response) => {
        const productList = response.rows.map((item) => ({
          ...item,
          selected: false,
        }));
        this.$set(this, "ordersProductList", productList);
        this.returnDialogVisible = true;
      });
      getProcuredOrderAmountDueById(row.ordersId).then((response) => {
        this.maxRefundAmount = response.maxRefundAmount;
      });
    },
    // 处理SKU选择变化
    handleSkuSelect(item) {
      if (item.selected) {
        // 添加到已选择列表
        const newItem = {
          sku: item.sku,
          productId: item.productId,
          productName: item.productName,
          availableQty: item.availableQty,
          purchaseQty: item.purchaseQty,
          quantity: null,
          amount: item.amount,
          freight: "",
          currentAmount: "",
        };
        this.selectedSkus.push(newItem);
      } else {
        // 从已选择列表中移除
        const index = this.selectedSkus.findIndex((i) => i.sku === item.sku);
        if (index !== -1) {
          this.selectedSkus.splice(index, 1);
        }
      }
      this.calculateTotalAmount();
    },
    // 计算单个商品金额
    calculateItemAmount(item) {
      const quantity = parseInt(item.quantity) || 0;
      const amount = parseFloat(item.amount) || 0;
      this.calculateTotalAmount();
      return (quantity * amount).toFixed(2);
    },
    // 处理支付方式改变
    handlePaymentType(val) {
      if (val == "2") {
        this.spanTitle = "最大退款采购数量：";
      } else {
        this.spanTitle = "最大退款库存数量：";
      }
      // 重置数量字段
      this.selectedSkus.forEach((item) => {
        item.quantity = "";
        item.freight = "";
        item.currentAmount = "";
      });
    },
    // 计算总退款金额
    calculateTotalAmount() {
      // 如果是手动输入模式，不自动计算
      let totalAmount = 0;

      // 计算所有选中商品的金额和运费
      this.selectedSkus.forEach((item) => {
        const quantity = parseInt(item.quantity) || 0;
        const amount = parseFloat(item.currentAmount) || 0;
        const freight = parseFloat(item.freight) || 0;
        totalAmount += quantity * amount + freight;
      });

      // 更新总退款金额
      this.returnForm.returnAmount = totalAmount.toFixed(2);
    },
    // 退款方式变化处理
    // handlePaymentTypeChange(value) {
    //   if (value === "0") {
    //     // 仅退款
    //     // 将所有已选SKU的数量设为0
    //     this.selectedSkus.forEach((item) => {
    //       item.quantity = "0";
    //     });
    //   } else {
    //     this.selectedSkus.forEach((item) => {
    //       item.quantity = "";
    //     });
    //   }
    // },
    getLimitQty(item) {
      if (this.returnForm.paymentType === "2") {
        return item.purchaseQty;
      }
      return item.availableQty;
    },
    async submitFormReturn() {
      // 如果没有选择任何SKU
      if (this.selectedSkus.length === 0) {
        this.$message.error("请至少选择一个SKU");
        return;
      }

      // 基础验证：备注和退款金额
      if (!this.returnForm.returnAmount) {
        this.$message.error("请输退款金额");
        return;
      }

      // 退款金额必须是数字且大于0
      const refundAmount = parseFloat(this.returnForm.returnAmount);
      if (isNaN(refundAmount) || refundAmount <= 0) {
        this.$message.error("退款金额，必须大于0");
        return;
      }

      // 检查退款金额是否超出最大限制
      const maxAmount = parseFloat(this.maxRefundAmount);
      if (refundAmount > maxAmount) {
        this.$message.error(
          `退款金额，不能大于最大可退款金额${this.maxRefundAmount}`
        );
        return;
      }

      // 基础验证：备注和退款金额
      if (
        !this.returnForm.returnRemark ||
        this.returnForm.returnRemark.trim() === ""
      ) {
        this.$message.error("退款备注不能为空");
        return;
      }
      // 仅退款时检查库存并提示
      if (this.returnForm.paymentType === "2") {
        const hasStockItems = this.selectedSkus.filter(
          (item) => item.availableQty > 0
        );

        if (hasStockItems.length > 0) {
          const stockMessages = hasStockItems
            .map((item) => `${item.sku}有库存${item.availableQty}`)
            .join("，");

          // 显示确认对话框
          const confirmed = await this.$confirm(
            `${stockMessages}，是否继续提交？`,
            "库存提示",
            {
              confirmButtonText: "继续提交",
              cancelButtonText: "取消",
              type: "warning",
            }
          ).catch(() => false);

          if (!confirmed) {
            return; // 用户取消，不继续提交
          }
        }
      }
      // 根据退款方式进行不同验证
      if (
        this.returnForm.paymentType === "2" ||
        this.returnForm.paymentType === "3"
      ) {
        // 退货退款
        // 验证每个选中SKU的退货数量
        for (const item of this.selectedSkus) {
          if (!item.quantity || item.quantity.trim() === "") {
            this.$message.error(`SKU ${item.sku} 的退货数量，不能为空`);
            return;
          }

          const quantity = parseInt(item.quantity);
          if (isNaN(quantity) || quantity < 0) {
            this.$message.error(`SKU ${item.sku} 的退货数量，不能小于0`);
            return;
          }

          const maxQuantity =
            this.returnForm.paymentType === "2"
              ? parseInt(item.purchaseQty)
              : parseInt(item.availableQty);
          if (quantity > maxQuantity) {
            this.$message.error(
              `SKU ${item.sku} 的退货数量，不能超过最大可退数量 ${maxQuantity}`
            );
            return;
          }
        }
      }

      // 所有验证通过，准备提交数据
      const submitData = {
        ordersId: this.currentOrder.ordersId,
        paymentType: this.returnForm.paymentType,
        returnAmount: this.returnForm.returnAmount,
        returnRemark: this.returnForm.returnRemark,
        items: this.selectedSkus.map((item) => ({
          sku: item.sku,
          productId: item.productId,
          quantity: item.quantity,
          amount: item.currentAmount * item.quantity,
          freight: item.freight,
        })),
      };
      // 避免重复提交
      if (this.isSubmitting) return;
      let originalPath = this.$route.path; // 当前路径
      let componentPath = "procured/ProcuredOrdersReturn/index"; //formatPath(originalPath);
      try {
        // 执行提交操作
        await addPaymentReturnQuash(
          submitData,
          componentPath,
          submitData.ordersId
        );
        this.getList();
        this.$modal.msgSuccess("申请退款成功！");
        this.returnDialogVisible = false; // 关闭对话框
      } catch (error) {
        this.$modal.msgError("提交审请退款中，请勿重复提交");
      } finally {
        this.isSubmitting = false; // 请求完成后解锁
      }
    },
    formatApplyAmount(row) {
      const amt =
        row.payableAmount != null
          ? row.payableAmount
          : row.prepaymentAmount != null
            ? row.prepaymentAmount
            : row.returnAmount != null
              ? row.returnAmount
              : 0;
      return amt.toFixed(2);
    },
    // 自动计算单个商品金额
    autoCalculateItemAmount(item) {
      const quantity = parseInt(item.quantity) || 0;
      const amount = parseFloat(item.amount) || 0;
      item.currentAmount = (quantity * amount).toFixed(2);
      this.calculateTotalAmount();
    },

    /////////////////////////////////////////////////退款结束/////////////////////////////////////////////////

    /** 采购订单商品序号 */
    rowOrdersProductIndex({ row, rowIndex }) {
      const baseIndex = `row-${rowIndex}`;
      if (row.returnCompletedStatus == 1 || row.returnCompletedStatus == "1") {
        console.log("应用 disabled-row 样式"); // 调试输出
        return `${baseIndex} disabled-row`;
      }
      return `${baseIndex} ${row.styleClass || ""}`;
    },
    tableRowClassName({ row }) {
      // 如果行数据有styleClass属性且不为空，则返回该样式类名
      return row.styleClass || "";
    },
    //撤回订单
    handleCancel(row) {
      this.$confirm("确认撤回该订单吗？", "系统提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        showInput: true, // 启用输入框
        inputPlaceholder: "请输入撤回原因", // 输入框提示文字
      })
        .then(({ value }) => {
          // value 包含用户输入的内容
          if (!value || value.trim() === "") {
            this.$message.warning("请填写撤回原因");
            return;
          }
          if (this.isSubmitting) return;
          // 处理撤回逻辑，传入value作为原因
          try {
            // 执行提交操作
            revokeProcuredOrders(row.ordersId, value);
            this.getList();
            this.$modal.msgSuccess("撤回订单成功！");
          } catch (error) {
            this.$modal.msgError("提交撤回订单中，请勿重复提交");
          } finally {
            this.isSubmitting = false; // 请求完成后解锁
          }
        })
        .catch(() => {
          // 用户点击取消
        });
    },
  },
};
</script>
<style scoped>
.auditStyle {
  width: 1166px;
}

.el-dialog__body {
  padding: 0px 20px;
  color: #606266;
  font-size: 14px;
  word-break: break-all;
}

.show-frame {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  width: 100%;
  height: 70px;
  margin-bottom: 10px;
}

.show-frame-container {
  overflow: auto;
  height: 560px;
  /* 设置容器的高度 */
}

/*
.el-image {
  border-radius: 5px;
  background-color: #ebeef5;
  box-shadow: 0 0 5px 1px #ccc;
  transform: translateY(9px);
  left: 19px;
} */

.plan-size {
  display: block;
  transform: translateY(-60px);
  margin-left: 94px;
  width: 30%;
}

.h1,
.h2,
.h3,
.h4,
.h5,
.h6,
h1,
h2,
h3,
h4,
h5,
h6 {
  font-family: inherit;
  font-weight: 500;
  line-height: 1.1;
  color: black;
  font-weight: bold;
}

.singleHanded-css {
  display: block;
  margin-left: 94px;
  margin-top: -66px;
}

.planNumber-css {
  display: block;
  cursor: pointer;
  z-index: 10;
  margin-top: -50px;
  margin-left: 375px;
  width: 20%;
}

.mannerName-css {
  display: block;
  margin-top: 11px;
  margin-left: 375px;
}

.paymentRequestCode-css {
  display: block;
  cursor: pointer;
  margin-top: -50px;
  margin-left: 685px;
  width: 20%;
}

.paymentAmount-css {
  display: block;
  margin-top: 11px;
  margin-left: 685px;
}

.shipTime-css {
  display: block;
  margin-top: -47px;
  margin-left: 944px;
  width: 15%;
}

.planStatus-css {
  display: block;
  margin-left: 944px;
  width: 15%;
}

.center-title .el-drawer__title {
  text-align: center;
}

.drawerValueUserImg {
  display: block;
}

.drawerValueSingleHanded {
  display: block;
  margin-top: -65px;
  margin-left: 96px;
}

.drawerValuePlanStatus {
  display: block;
  margin-top: -13px;
  margin-left: 98px;
}

.el-descriptions--mini:not(.is-bordered) .el-descriptions-item__cell {
  padding-bottom: 9px;
  font-size: 13px;
}

.margin-top {
  display: block;
  margin-top: 16px;
  margin-left: 20px;
}

.margin-top1 {
  display: block;
  margin-top: -47px;
  margin-left: 89px;
}

hr {
  border-color: #0000;
  height: 7px;
  background-color: #f3f3f3;
}

.el-descriptions-item__label.has-colon::after {
  content: ":";
  position: relative;
  top: -0.5px;
  display: none;
}

.sponsor {
  font-size: 14px;
  display: block;
  margin-top: -41px;
  margin-left: 96px;
}

.sponsor-name {
  font-size: 12px;
  display: block;
  margin-top: 4px;
  margin-left: 96px;
  color: #6f7174;
}

.sponsor-time {
  font-size: 12px;
  display: block;
  margin-top: -34px;
  margin-left: 439px;
  color: #6f7174;
}

.postUserDept-css {
  display: block;
  margin-top: 30px;
  height: auto;
}

.postUserDept-postName {
  font-size: 12px;
  display: block;
  margin-top: 3px;
  margin-left: 439px;
  color: #6f7174;
}

.block {
  display: block;
  margin-left: 19px;
  margin-top: 55px;
}

.approval {
  position: sticky;
  bottom: 20px;
  flex-direction: column;
  align-items: flex-start;
  /* 靠左对齐 */
  margin-top: 10px;
}

.processRemark-input {
  width: 70%;
  /* 占满可用宽度 */
  margin-bottom: 20px;
  /* 与按钮组的间距 */
}

.button-group {
  display: flex;
  float: right;
  transform: translateX(-30%);
  /* 修正因right的偏移 */
  gap: 50px;
  /* 按钮之间的间距 */
}

._scroll-container {
  margin-top: 45px;
  height: 300px;
  max-height: 350px;
  /* 设置最大高度 */
  overflow-y: auto;
  /* 垂直滚动 */
  border: 2px solid #ccc;
  /* 边框可选 */
}

/* 定义red样式类 */
/deep/ .red {
  background-color: #ffebeb !important;
  color: #f56c6c;
}

/deep/ .el-table .el-table__row.disabled-row {
  background-color: #c7c7c7 !important;
  opacity: 0.6 !important;
}

/* /deep/ .el-table .el-table__row.disabled-row td {
  background-color: #ada5a5 !important;
  color: #ffffff !important;
} */

.el-table .disabled-row .el-input input,
.el-table .disabled-row .el-select .el-input__inner,
.el-table .disabled-row .el-checkbox,
.el-table .disabled-row .el-date-editor,
.el-table .disabled-row .el-textarea textarea {
  background-color: #f5f7fa !important;
  color: #c0c4cc !important;
  cursor: not-allowed !important;
  pointer-events: none !important;
}
</style>
